"""
日志模块
"""

import os
from logging.handlers import TimedRotatingFileHandler

from config.config import Config,LOG_PATH
import logging

class Logger:

    c = Config().get('log')
    logging.root.setLevel(logging.NOTSET)
    c = Config().get('log')
    log_file_name = c.get('file_name') if c and c.get('file_name') else 'test.log'  # 日志文件
    backup_count = c.get('backup') if c and c.get('backup') else 5  # 保留的日志数量
    # 日志输出级别
    console_output_level = c.get('console_level') if c and c.get('console_level') else 'WARNING'
    file_output_level = c.get('file_level') if c and c.get('file_level') else 'DEBUG'
    # 日志输出格式
    pattern = c.get('pattern') if c and c.get('pattern') else '%(asctime)s - %(name)s - %(levelname)s - %(message)s'
    formatter = logging.Formatter(pattern)
    logger = None

    @classmethod
    def get_logger(cls, module_name):
        """
        日志生成器
        :param module_name: 日志记录的模块名
        :return: 返回一个日志对象
        """

        if cls.logger is None:
            cls.logger = logging.getLogger(str(module_name))
            cls.logger.setLevel(logging.INFO)
            log_file_name = cls.c.get('file_name') if cls.c and cls.c.get('file_name') else 'test' + '.log' # 日志文件
            backup_count = cls.c.get('backup') if cls.c and cls.c.get('backup') else 5  # 保留的日志数量
            if not os.path.exists(LOG_PATH):
                os.mkdir(LOG_PATH)
            # filename = os.path.join(LOG_PATH, str(TimeUtil.get_time()),'.log')
            # handler = logging.FileHandler(filename=filename, encoding='utf-8')
            # formatter = logging.Formatter(
            #     f'%(asctime)s - {module_name} - %(levelname)s - %(message)s')
            # handler.setFormatter(formatter)
            # cls.logger.addHandler(handler)

            if not cls.logger.handlers:  # 避免重复日志
                console_handler = logging.StreamHandler()
                console_handler.setFormatter(cls.formatter)
                console_handler.setLevel(cls.console_output_level)
                cls.logger.addHandler(console_handler)

                # 每天重新创建一个日志文件，最多保留backup_count份
                file_handler = TimedRotatingFileHandler(filename=os.path.join(LOG_PATH, cls.log_file_name),
                                                        when='D',
                                                        interval=1,
                                                        backupCount=cls.backup_count,
                                                        delay=True,
                                                        encoding='utf-8'
                                                        )
                file_handler.setFormatter(cls.formatter)
                file_handler.setLevel(cls.file_output_level)
                cls.logger.addHandler(file_handler)

        return cls.logger